<template>

</template>

<script setup name="HazardAlarm">
import {ElNotification} from "element-plus";
import useUserStore from "@/store/modules/user.js";
import {getHazardAlarm} from "@/api/business/hazard.js";
import {setDeltaId} from "@/utils/auth.js";
import {useRouter} from "vue-router";
import {sleep} from "@/utils/index.js";

const router = useRouter()
const userStore = useUserStore()

const checkAlarm = async () => {
    let payload = undefined
    if (userStore.deltaId) payload = {deltaId: userStore.deltaId}
    const {data} = await getHazardAlarm(payload)
    if (!data.deltaId) return

    userStore.deltaId = data.deltaId
    setDeltaId(data.deltaId) // keep into cookie at the same time.

    const title = payload?.deltaId ? '隐患更新警告' : '隐患统计警告'
    createHazardAlarmNotification(data.majorRecord, title)
    if (data.majorRecord) await sleep(3000)
    createHazardAlarmNotification(data.delayedRecord, title)
}

function createHazardAlarmNotification(record, title) {
    if (!record?.hazardIds) return
    const hazardCount = record.hazardIds.split(',').length
    if (!hazardCount) return

    let msgHtml = '<div class="text-content cursor-pointer">'
    msgHtml += '<div class="mt20 mb20">发现' + hazardCount + '条隐患' + record.type + '</div>'
    msgHtml += '<a class="link-type">去查看</a>'
    msgHtml += '</div>'

    const notifier = ElNotification({
        title: title,
        type: 'warning',
        duration: 0,
        dangerouslyUseHTMLString: true,
        message: msgHtml,
        onClick: () => {
            notifier.close()

            // go to hazard list page
            const payload = {id: record.id, tag: `${record.type}通知（${hazardCount}）`}
            const query = {alarm: encodeURIComponent(JSON.stringify(payload))}
            router.push({path: '/docs/hazard/list', query})
        }
    })
}

onMounted(() => {
    const interval = 1 * 60 * 1000 // 5分钟
    setInterval(() => checkAlarm(), interval)
    checkAlarm() // call immediately once
})
</script>

<style scoped>

</style>